﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Infrastructure.Lib.Core
{
    public static partial class JsonHelper
    {
        /// <summary>
        ///把指定类型转换为Json
        /// </summary>
        /// <param name="list">集合</param>
        /// <returns></returns>
        public static string ObjectToJson(this object obj, bool selfFormat = false)
        {
            if (selfFormat)
            {
                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                return JsonConvert.SerializeObject(obj, timeFormat);
            }
            else
            {
                return JsonConvert.SerializeObject(obj);
            }
        }

        /// <summary>
        /// 把Json转换为指定T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T JsonToModels<T>(this string jsonStr, bool selfFormat = false)
        {
            if (selfFormat)
            {
                IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
                timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
                return JsonConvert.DeserializeObject<T>(jsonStr, timeFormat);
            }
            else
            {
                return JsonConvert.DeserializeObject<T>(jsonStr);
            }
        }
    }
}
